﻿
namespace NYTMovieReviews
{
    using System;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Interactivity;
    using Microsoft.Phone.Controls;

    public class DetailNavigateBehavior : Behavior<ListBox>
    {
        public DetailNavigateBehavior()
        {
            // Insert code required on object creation below this point.

            //
            // The line of code below sets up the relationship between the command and the function
            // to call. Uncomment the below line and add a reference to Microsoft.Expression.Interactions
            // if you choose to use the commented out version of MyFunction and MyCommand instead of
            // creating your own implementation.
            //
            // The documentation will provide you with an example of a simple command implementation
            // you can use instead of using ActionCommand and referencing the Interactions assembly.
            //
            //this.MyCommand = new ActionCommand(this.MyFunction);
        }

        protected override void OnAttached()
        {
            base.OnAttached();

            this.AssociatedObject.SelectionChanged += new System.Windows.Controls.SelectionChangedEventHandler(this.AssociatedObject_SelectionChanged);
        }

        protected override void OnDetaching()
        {
            base.OnDetaching();

            // Insert code that you would want run when the Behavior is removed from an object.
        }

        private void AssociatedObject_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            if (this.AssociatedObject.SelectedIndex == -1)
            {
                return;
            }

            var pivot = this.AssociatedObject.DataContext as MoviePivot;

            var uriString = string.Format("/DetailsPage.xaml?pivot={0}&index={1}", pivot.Reviews.Order, this.AssociatedObject.SelectedIndex);

            var frame = Application.Current.RootVisual as PhoneApplicationFrame;

            if (frame.Navigate(new Uri(uriString, UriKind.Relative)))
            {
                this.AssociatedObject.SelectedIndex = -1;
            }
        }

        /*
        public ICommand MyCommand
        {
            get;
            private set;
        }
         
        private void MyFunction()
        {
            // Insert code that defines what the behavior will do when invoked.
        }
        */
    }
}